package com.ltcode.log.starter.utils;


import com.ltcode.log.starter.entity.DataEntity;
import com.ltcode.log.starter.entity.ThreadLocalEntity;

public class LogUtils {
    // 使用 InheritableThreadLocal 以支持子线程继承父线程的值
    private static final ThreadLocal<ThreadLocalEntity> inheritableThreadLocal = new InheritableThreadLocal<>();

    public static void put(DataEntity dataEntity) {
        ThreadLocalEntity entity = inheritableThreadLocal.get();
        if (entity == null) {
            entity = new ThreadLocalEntity();
            inheritableThreadLocal.set(entity);
        }
        entity.pushDataEntity(dataEntity);
    }

    public static DataEntity get() {
        ThreadLocalEntity entity = inheritableThreadLocal.get();
        if (entity != null) {
            return entity.peekDataEntity();
        }
        return null;
    }

    public static void remove() {
        ThreadLocalEntity entity = inheritableThreadLocal.get();
        if (entity != null) {
            entity.popDataEntity();
            if (entity.peekDataEntity() == null) {
                inheritableThreadLocal.remove();
            }
        }
    }

    // 获取当前线程的日志上下文
    public static ThreadLocalEntity getThreadLocalEntity() {
        return inheritableThreadLocal.get();
    }

    // 设置当前线程的日志上下文
    public static void setThreadLocalEntity(ThreadLocalEntity entity) {
        inheritableThreadLocal.set(entity);
    }

    // 创建一个新的数据实体并设置到当前线程
    public static void createAndSetNewDataEntity() {
        ThreadLocalEntity entity = getThreadLocalEntity();
        if (entity == null) {
            entity = new ThreadLocalEntity();
            setThreadLocalEntity(entity);
        }
    }

    // 安全地获取当前数据实体，避免空指针异常
    public static DataEntity safeGetDataEntity() {
        ThreadLocalEntity entity = getThreadLocalEntity();
        return entity != null && !entity.getDataEntityStack().isEmpty() ? 
               entity.peekDataEntity() : new DataEntity();
    }
}